package top.mable.common.util;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ClusterLock {

    @Autowired
    RedissonClient redissonClient;

    public static final String LOCK_PREFIX = "CLUSTER_LOCK_";

    public boolean tryLock(String key, long waitTime, TimeUnit timeUnit){
        RLock lock = redissonClient.getLock(LOCK_PREFIX + key);
        try {
            return lock.tryLock(waitTime, -1, timeUnit);
        } catch (InterruptedException e) {
            log.error("获取锁{}中断",key);
            Thread.interrupted();
        }

        return false;
    }

    public boolean tryLock(String key, long waitTime,long leaseTime, TimeUnit timeUnit){
        RLock lock = redissonClient.getLock(LOCK_PREFIX + key);
        try {
            return lock.tryLock(waitTime, leaseTime, timeUnit);
        } catch (InterruptedException e) {
            log.error("获取锁{}中断",key);
            Thread.interrupted();
        }
        return false;
    }

    public boolean tryLock(String key){
        return tryLock(key,10000,TimeUnit.MILLISECONDS);
    }


    public void  unlock(String key){

        redissonClient.getLock(LOCK_PREFIX + key).unlock();
    }


}
